﻿using AutoMapper;
using B.S.BaseData.Domain.Entities.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.WriteAPI.Utils;
using B.S.DataBase.EFCoreServiers.Dtos.Permissions;
using B.S.DataBase.EFCoreServiers.IServices.Dtpes;
using B.S.DataBase.EFCoreServiers.IServices.Permissions;
using B.S.DataBase.EFCoreServiers.Services.Depts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace B.S.BaseData.WriteAPI.Controllers
{
    /// <summary>
    /// 权限管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    [ApiExplorerSettings(GroupName = "Perms")]
    public class PermissionController : ControllerBase
    {
        private readonly IPermissionServices permission;
        private readonly ILogger<PermissionController> _logger;

        public PermissionController(IPermissionServices permission, ILogger<PermissionController> logger)
        {
            this.permission = permission;
            _logger = logger;
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        [HttpPost]
        [LogOperation("权限管理", "新增", "添加新的权限项")]
        public async Task<ApiResult> AddPermissiontAsync(AddPermissionDto permissionDto)
        {
            try
            {
                var res = await permission.AddPermissiontAsync(permissionDto);
                if (res != null)
                {
                    _logger.LogInformation("开始添加权限: ", permissionDto.PermissionName);
                }
                return res;
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("添加权限失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 修改角色权限
        /// </summary>
        [HttpPost]
        [LogOperation("权限管理", "修改", "修改角色权限配置")]
        public async Task<ApiResult> ModifyRolePermissionsAsync(ModifyRolePermissionsDto modifyRolePermissionsDto)
        {
            try
            {
                _logger.LogInformation($"开始修改角色(ID:{modifyRolePermissionsDto.RoleId})的权限");
                var res = await permission.ModifyRolePermissionsAsync(modifyRolePermissionsDto);
                return res;
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("修改角色权限失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }
    }
}
